import Vue from "vue";
import VueRouter from "vue-router";
import Index from "../views/Index.vue";
import store from "@/store";

// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/index",
    name: "index",
    component: Index,
  },
  {
    path: "/goods",
    name: "goods",
    component: () =>
      import(/* webpackChunkName: "goods" */ "../views/Goods.vue"),
  },
  {
    path: "/order",
    name: "order",
    component: () =>
      import(/* webpackChunkName: "order" */ "../views/Order.vue"),
  },
  {
    path: "/free",
    name: "free",
    component: () => import(/* webpackChunkName: "free" */ "../views/Free.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () => import(/* webpackChunkName: "user" */ "../views/User.vue"),

    //路由独享守卫  参数同全局守卫一致
    // beforeEnter: (to, from, next) => {
    //   console.log("to1:", to, "from1:", from);
    //   //则需要获取是否存在token
    //   let token = localStorage.getItem("x-auth-token");
    //   if (token) {
    //     //如果存在正常进入user页面
    //     next();
    //   } else {
    //     //否则提示你还没有登录
    //     store.dispatch("showToast/asyncIsShowToast", {
    //       isShow: true,
    //       msg: "你还没有登录",
    //       type: "warning",
    //     });
    //   }
    // },
    redirect: "/user/cart",
    children: [
      {
        path: "/user/cart",
        name: "cart",
        component: () =>
          import(/* webpackChunkName: "cart" */ "../components/user/Cart.vue"),
      },
    ],
  },
  {
    path: "/details",
    name: "details",
    component: () =>
      import(/* webpackChunkName: "details" */ "../views/Details.vue"),
  },
  {
    // 所有路径都能进入---匹配到所有路径
    path: "*",
    name: "error",
    component: () =>
      import(/* webpackChunkName: "cart" */ "../views/Error.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
// 全局路由导航守卫
// router.beforeEach((to, from, next) => {
//   // 有token就表示已经登录
//   // 想要进入个人中心页面，必须有登录标识token
//   // console.log("to:", to);
//   // console.log("from:", from);
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token");
//     // 此时必须要有token
//     if (token) {
//       next(); // next()去到to所对应的路由界面
//     } else {
//       // 提示没有登录
//       store.dispatch("showToast/asyncChangeIsShowToast", {
//         isShow: true,
//         msg: "你还没有登录！",
//         type: "warning",
//       });
//     }
//     return; // 需要些return，防止执行完上面的next()，还继续执行下面的next()
//   }
//   // 如果不是去往个人中心的路由，则直接通过守卫，去到to所对应的路由界面
//   next();
// });

export default router;
